package com.fly.lambda;

import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

import org.junit.jupiter.api.Test;

public class LambdaDemo
{
    @Test
    public void test1()
    {
        Runnable noArguments = () -> System.out.println("Hello World");
        new Thread(noArguments).start();
        
        // 简化写法
        new Thread(() -> System.out.println("Hello World")).start();
    }
    
    @Test
    public void test11()
    {
        Runnable multiStatement = () -> {
            System.out.print("Hello");
            System.out.println(" World");
        };
        new Thread(multiStatement).start();
    }
    
    @Test
    public void test12()
    {
        ActionListener oneArgument = event -> System.out.println("button clicked");
        System.out.println(oneArgument);
    }
    
    @Test
    public void test2()
    {
        // 数学运算
        BinaryOperator<Long> add = (x, y) -> x + y;
        System.out.println(add.apply(10L, 20L));
        
        BinaryOperator<Integer> add2 = (x, y) -> x + y;
        System.out.println(add2.apply(20, 30));
        
        BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;
        System.out.println(addExplicit.apply(10L, 20L));
    }
    
    String name[] = {"张三", "李四", "王五", "孙刘", "赵强", "李明", "赵强", "汪汪"};
    
    /**
     * 统计数组中某元素出现的个数
     * 
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    @Test
    public void test3()
    {
        long num = Arrays.stream(name).filter(x -> x.equals("赵强")).count();
        System.out.println(num);
    }
    
    /**
     * 数组去重并转化成集合存储
     * 
     * @see [类、类#方法、类#成员]
     */
    @Test
    public void test5()
    {
        List<String> list = Arrays.stream(name).filter(x -> !x.equals("赵强")).collect(Collectors.toList());
        System.out.println(list);
    }
    
    /**
     * 数组去重，并对元素加后缀
     * 
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    @Test
    public void test6()
    {
        List<String> list = Arrays.stream(name).filter(x -> !x.equals("赵强")).map(y -> y + "你好").collect(Collectors.toList());
        System.out.println(list);
    }
    
    /**
     * 数组求和
     * 
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    @Test
    public void test7()
    {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 8, 9, 10};
        
        // for循环
        int count = 0;
        for (int i = 0; i < a.length; i++)
        {
            count += a[i];
        }
        System.out.println(count);
        
        // foreach
        count = 0;
        for (int i : a)
        {
            count += i;
        }
        System.out.println(count);
        
        // Lambda
        int num = Arrays.stream(a).reduce(0, (b, c) -> b + c);
        System.out.println(num);
    }
}
